#
# P4Prefs.py
#
# Preferences for the SNiFF+ 3.x Perforce Adapter
#
# Author: Martin Oberhuber
# Copyright (c) 1998, 1999 TakeFive Software, Salzburg
#
# History:
#	1999-05-03  MOB  Created
#

# Standard Modules
import string, os
import vcs
from vcs import SYSTEM, WINDOWS, UNIX, NL, TRUE, FALSE

# Perforce Modules
import P4Dialogs

#----------Constants-----------------------------------------------------
ModMark = "(P4Prefs) "

TEST = 0				# Debugging enabled
TEST2 = 0				# HEAVY Debugging including output of commands

P4Error = 'P4Error'		# P4 Exception

StatCacheTimeout = 10	# timeout period for which things acquired by fstat are considered valid
ErrorDialogTimeout = 1	# don't show same error dialog again after this many seconds
AllowExclusiveLocking = 1	# allow exclusive Locking by Lock/Unlock
ConcurrentLockOnCheckoutE=0	# Concurrent Lock preferred: If Checkout/Exclusive requested, checkout concurrent instead
DefaultFiletype = "xbinary"	# default for the Filetype dialog
LockersShowVersion = 1	# show local / head version and update signs
LockersShowFiletype = 0	# show <filetype> in lockers column
LockersShowBranch = 0	# show depot string in lockers column

#----------Helper functions----------------------------------------------

# Internal Dictionary to hold P4 Client associations with a WE Root
_P4Clients = {}
def GetClient(pweRoot, pweName=""):
	"""return the Perforce Client name for a given Working Environment Root."""
	marker=ModMark+"GetClient: "
	if TEST: print marker
	global _P4Clients
	try:
		theClient = _P4Clients[pweRoot]
	except:
		# client has not yet been set
		if TEST: print marker,"Client not yet set..."
		try:
			theClient=string.strip(open(vcs.joinpath(pweRoot,".p4client")).read())
			if TEST: print theClient
		except:
			try:
				theClient = os.environ["SNIFF_P4CLIENT"]
			except:
				# OS-Var SNIFF_P4CLIENT not set, test P4CLIENT
				try:
					theClient = os.environ["P4CLIENT"]
					print os.environ["P4CLIENT"]
				except:				
					# OS-Var P4CLIENT not set, test for username and hostname
					if SYSTEM==WINDOWS:
						try:
							#theClient = os.environ["USERNAME"] + "-" + string.swapcase(os.environ["COMPUTERNAME"])
							theClient = string.strip(string.swapcase(os.environ["COMPUTERNAME"]))
						except:
							theClient = "USE_WE"					
					elif SYSTEM==UNIX:
						try:
							#theClient = os.environ["USER"] + "-" + vcs.getoutput("hostname")
							theClient = string.strip(vcs.getoutput("hostname"))
						except:
							theClient = "USE_WE"					
					else: theClient = "USE_WE"
			if not theClient or theClient == "USE_WE":
				if not pweName:
					# cannot auto-set Name to WE-like client
					theClient = P4Dialogs.AskQuestionDialog("Set Perforce Client", "New Client name:", "")
					if not theClient:
						print "CANCEL pressed, aborting...."
						raise P4Error
				else:
					theClient = ClientName(pweRoot, pweName)
		_P4Clients[pweRoot]=theClient
	return theClient

def SetClient(pweRoot, clientName):
	"""Associate a Perforce Client Name with a Working Environment Root."""
	marker=ModMark+"SetClient: "
	global _P4Clients
	if string.find(clientName,":") > 0:
		# Convert a SNiFF Working Environment name to a client name
		clientName = ClientName(pweRoot, clientName)
	if TEST: print marker, "Setting client @B",clientName,"@B to @B",pweRoot,"@B"
	_P4Clients[pweRoot] = clientName

def ClientName(PWERoot, PWEName):
	marker=ModMark+"ClientName: "
	if TEST: print marker
	theColon = string.find(PWEName,":")
	theSpace = string.rfind(PWEName[:theColon]," ")
	if theSpace > 0:
		userName = PWEName[:theSpace] + "-"
	else:
		userName = ""
	WEName = PWEName[theColon+1:]
	clientName = userName + WEName
	return clientName

# given the full log message of a revision, construct the
# abridged version which can be used for the changeset name in SNiFF
def SymbolFromComment(comm):
	tr = string.maketrans(" *,:;?.!#$()[]{}\t\n\'\"",20*"_")
	sym = string.translate(comm[:22],tr)
	return sym

# given a full //depot style branch name and a full //depot style
# base repositoryFile, construct the branch indicator by comparing
# the two and throwing away identic parts.
def MakeBranchName(BranchName, BaseName):
	try:
		(brName, brRev) = string.split(BranchName, "#")
	except:
		brName = BranchName
	# skip the file names
	brList = string.split(brName,"/")[:-1]
	baseList = string.split(BaseName, "/")[:-1]
	curIdx = len(brList)-1
	while curIdx >= 0:
		if brList[curIdx] in baseList:
			baseIdx=len(baseList)-1
			while baseIdx >= 0:
				if brList[curIdx] == baseList[baseIdx]:
					# don't allow mappings to be crossed
					del baseList[baseIdx:]
					break
				baseIdx = baseIdx - 1
			del brList[curIdx]
		curIdx = curIdx - 1
	res = string.join(brList,"/")
	if not res or res == "/":
		res = "main"
	return res


# this function returns the current tempdir
# it looks for the environment variables TMPDIR, TEMP and TMP
# in this order, if no variable present, current working directory is used
_TempDir = ""
def getTempDir():
	import os
	global _TempDir
	if _TempDir:
		return _TempDir
	retTempDir = os.getcwd()
	# check TMPDIR
	if os.environ.has_key("TMPDIR"):
		retTempDir = os.environ["TMPDIR"]
	else:
		if os.environ.has_key("tmpdir"):
			retTempDir = os.environ["tmpdir"]
		else:
			if os.environ.has_key("TEMP"):
				retTempDir = os.environ["TEMP"]
			else:
				if os.environ.has_key("temp"):
					retTempDir = os.environ["temp"]
				else:
					if os.environ.has_key("TMP"):
						retTempDir = os.environ["TMP"]
					else:
						if os.environ.has_key("tmp"):
							retTempDir = os.environ["tmp"]
						else:
							# Nothing Set
							if SYSTEM==WINDOWS:
								retTempDir = "C:/TEMP"
							else:
								retTempDir = "/tmp"
	_TempDir = os.path.normpath(retTempDir)
	return _TempDir

# this function returns a unique temoprary filename
def tmpnam(prefix="p4_tmp_"):
	import tempfile, os
	tempfile.tempdir = getTempDir()
	tempfile.template = prefix
	return vcs.normpath(tempfile.mktemp())

#----------Tests----------------------------------------------------------

if __name__ == '__main__':
	pweRoot="/sapmnt/home1/d000723/WS/BIN/src"
	print ClientName(pweRoot, "mober PWE:BIN-src")
	# print GetClient(pweRoot)
